<?php
/**
 * 合作伙伴管理
 * Author: Zeon
 * Date: 2018/1/24
 * Created by Panxsoft.
 */

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Http\Models\Partner;
use App\Http\Requests\Admin\PartnerIndexRequest;
use App\Http\Requests\Admin\PartnerStoreRequest;
use App\Http\Requests\Admin\PartnerUpdateRequest;
use App\Services\Utils\ApiChecker;
use App\Services\Utils\ApiResponser;
use Illuminate\Http\Request;

class PartnerController extends Controller
{
    use ApiResponser,ApiChecker;

    /**
     *  返回合作伙伴的列表
     * @param PartnerIndexRequest $request
     * @return array|\Illuminate\Http\Response
     */
    public function index(PartnerIndexRequest $request)
    {
        $partners = (new Partner)->filterName($request->name)
            ->latest('priority')
            ->latest()
            ->paginate($request->per_page?:15);

        return $this->response(compact('partners'));
    }

    /**
     *  添加合作伙伴
     * @param PartnerStoreRequest $request
     * @return array|\Illuminate\Http\Response
     */
    public function store(PartnerStoreRequest $request)
    {
        $partner = $this->transformPartnerData($request);

        $stored = Partner::create($partner);

        return $this->response(compact('stored'));
    }

    /**
     *  更新合作伙伴的信息
     * @param PartnerUpdateRequest $request
     * @param $id
     * @return array|\Illuminate\Http\Response
     * @throws \App\Exceptions\AdminManageException
     */
    public function update(PartnerUpdateRequest $request, $id)
    {
        /** @var Partner $partner */
        $partner = (new Partner)->find($id);
            $this->checkItemExist($partner, '合作伙伴');

        $partner_info = $this->transformPartnerData($request);

        $updated = $partner->update($partner_info);

        return $this->response(compact('updated'));
    }

    /**
     *  删除合作伙伴的信息
     * @param $id
     * @return array|\Illuminate\Http\Response
     * @throws \App\Exceptions\AdminManageException
     * @throws \Exception
     */
    public function destroy($id)
    {
        /** @var Partner $partner */
        $partner = (new Partner)->find($id);
            $this->checkItemExist($partner, '合作伙伴');

        $deleted = $partner->delete();

        return $this->response(compact('deleted'));
    }

    /**
     * @param PartnerStoreRequest|PartnerStoreRequest|request $request
     * @return array
     */
    private function transformPartnerData(Request $request)
    {
        return [
            'name'     => $request->name,
            'logo'     => $request->logo,
            'url'      => $request->url,
            'remark'   => $request->remark,
            'priority' => $request->priority?:0,
        ];
    }
}